package com.ai.aicontact.common.tag;

import java.util.HashMap;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ai.aicontact.common.context.ContextHolder;
import com.ai.aicontact.common.entity.SysStaticData;
import com.ai.aicontact.common.service.SysStaticDataService;
import com.alibaba.fastjson.JSON;


public class StaticDataTag extends TagSupport {
	private static final long serialVersionUID = -3019487475793118426L;
	private String fields;
	
	private SysStaticDataService sysStaticDataService;
 
	
	public int doStartTag() throws JspException {
		StringBuilder sb = new StringBuilder();

		try {
			if (StringUtils.isEmpty(this.fields)) {
				return -1;
			}
			if(sysStaticDataService == null){
				sysStaticDataService = ContextHolder.getBean("sysStaticDataServiceImpl");
			}
			sb.append("<script type=\"text/javascript\">");

 			String[] keys = this.fields.split(",");
			for (int i = 0; i < keys.length; ++i) {
				String codeType = keys[i];
				List<SysStaticData> caches = sysStaticDataService.getStaticDataByCodyType(codeType);
				HashMap map = new HashMap();
				for (SysStaticData sysStaticData : caches) {
					map.put(sysStaticData.codeValue, sysStaticData.codeName );
				}
				sb.append("\n").append("var ").append(codeType.replaceAll("_", "").toLowerCase()).append("=").append(JSON.toJSONString(map)).append(";");
			}
			sb.append("</script>");

			this.pageContext.getOut().write(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	public int doEndTag() throws JspException {
		return 6;
	}

	public void release() {
		this.fields = null;
		super.release();
	}

	public String getFields() {
		return this.fields;
	}

	public void setFields(String fields) {
		this.fields = fields;
	}
}
